package com.msb.juc.c_021;

import java.lang.invoke.MethodHandles;
import java.lang.invoke.VarHandle;

/**
 * VarHandle可以把普通类的普通操作变成原子操作
 * <p>
 * VarHandle的效率比反射高，直接操作的是二进制码
 */
public class T02_VarHandle {
    int x = 8;
    private static VarHandle handle;

    static {
        try {
            handle = MethodHandles.lookup().findVarHandle(T02_VarHandle.class, "x", int.class);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        T02_VarHandle t = new T02_VarHandle();

        System.out.println((int) handle.get(t));

        handle.set(t, 9);
        System.out.println(t.x);

        handle.compareAndSet(t, 9, 10);
        System.out.println(t.x);

        handle.getAndAdd(t, 10);
        System.out.println(t.x);
    }
}
